<template>
  <div class="add-template-wrapper">
    <Form
      ref="form"
      :model="formData"
      :rules="rulesFormData"
      :label-width="80"
      class="add-form"
    >
      <FormItem label="名称：" prop="name" :show-message="false">
        <Input
          v-model="formData.name"
          :maxlength="128"
          placeholder="最大长度为128个字符"
          style="width: calc(100% - 60px); margin-bottom: 10px"
        ></Input>
      </FormItem>
      <FormItem label="文件：" prop="file" :show-message="false">
        <Upload
          ref="template-upload"
          v-model="formData.file"
          :format="['json', 'JSON']"
          action="/api/virtual/template/add"
          :before-upload="handleUpload"
          style="display: inline-block"
        >
          <Button icon="ios-cloud-upload-outline">选择文件</Button>
          <span v-if="formData.file">{{ formData.file.name }}</span>
        </Upload>
        <WarningTip content="请导入JSON格式文件" placement="right"></WarningTip>
        <!-- <span class="warn-tip"
          ><Icon type="ios-alert-outline" />请导入JSON格式文件</span
        > -->
        <div
          class="demo-upload-list"
          v-for="item in uploadList"
          :key="item.name"
        >
          <template v-if="item.status === 'finished'"> </template>
          <template v-else>
            <span style="margin-right: 5px">文件名：{{ item.name }}</span>
            <span style="margin-right: 5px"
              >文件大小：{{ getFileSize(item.size) }}</span
            >
            <span style="margin-right: 5px">导入速度：{{ speed }}</span>
            <Progress
              v-if="item.showProgress"
              :percent="item.percentage"
              hide-info
              :stroke-width="2"
            ></Progress>
          </template>
        </div>
        <p class="error-tip" v-if="showTip">文件格式错误，请导入JSON格式文件</p>
      </FormItem>
      <FormItem label="描述：" prop="desc" key="desc">
        <Input
          type="textarea"
          v-model="formData.desc"
          style="width: calc(100% - 60px)"
        ></Input>
      </FormItem>
      <FormItem class="flex-end mt10">
        <Button @click="handleReset('form')">重置</Button>
        <Button type="primary" @click="submitTem('form')">确定</Button>
      </FormItem>
    </Form>
  </div>
</template>
<script>
import encryption from '@/libs/encryption.js';
import { inPutTemFile } from '@/api/homer.js';
import {validateName128 } from '@/libs/reg.js'
export default {
    name: 'ImportTemplate',
    props: ['bucket','public'],
    data() {
        let September = sessionStorage.getItem('November');
        September = JSON.parse(encryption.SelfUseDecrypt(September));
        return {
            formData: {
                name: '',
                type: 'project',
                visibility: 'private',
                file: null,
                detail: '',
                desc: ''
            },
            loading: false,
            rulesFormData: {
              name: [
                { required: true, message: '名称不能为空', trigger: 'change' },
                { validator: validateName128, trigger: 'change' }],
                file: [{ required: true, message: '请导入文件' }]
            },
            uploadList: [],
            showTip: false
        };
    },
    computed: {},
    filters: {},
    watch: {
        show: function(show) {
            if (show) {
                this.showTip = false;
            }
      },
      public: {
        handler (val) {
           this.formData.visibility = val == 0 ? 'private' : 'share'
        },
        deep: true,
        immediate: true,
      },
    },
    methods: {
        getFormat() {
            return this[this.bucket].format;
        },
        handleFormatError(sss) {
            this.showTip = true;
        },
        handleUploadSize() {
            this.showTip = true;
        },
        getFileSize(size) {
            let fileSize;
            if (size > 1024 * 1024) {
                fileSize = (Math.round((size * 100) / (1024 * 1024)) / 100).toString() + 'MB';
            } else {
                fileSize = (Math.round((size * 100) / 1024) / 100).toString() + 'KB';
            }
            return fileSize;
        },
        getProgress(progressEvent) {
            var aaspeed = Number(progressEvent.loaded - this.loaded) || 0;
            this.loaded = progressEvent.loaded;
            if (aaspeed > 1024 * 1024) {
                this.speed =
                    (Math.round((aaspeed * 100) / (1024 * 1024)) / 100).toString() + 'MB/s';
            } else {
                this.speed = (Math.round((aaspeed * 100) / 1024) / 100).toString() + 'KB/s';
            }
        },
        // 提交表单
        submitTem(name) {
            let _this = this;
            _this.loading = true;
            this.$refs[name].validate((valid) => {
                if (valid) {
                    let params = JSON.stringify({
                        description: this.formData.desc,
                        fileData: this.formData.detail,
                        name: this.formData.name,
                        type: 'project',
                        visibility: this.formData.visibility
                    });
                    inPutTemFile(params).then((data) => {
                        if (data.data.code === 1) {
                            _this.$Message.success({
                                content: '操作成功',
                                duration: 3
                            });
                            this.$refs[name].resetFields();
                            this.formData.desc = '';
                            this.$emit('on-success', data.data.data, this.bucket);
                        } else {
                            _this.$Message.error({
                                content: data.data.message,
                                duration: 3
                            });
                        }
                        _this.loading = false;
                    });
                } else {
                    _this.loading = false;
                    if (!this.formData.name) {
                        this.$Message.error('请输入名称');
                        return;
                    }
                    if (!this.formData.detail) {
                        this.$Message.error('请选择文件');
                        return;
                    }
                }
            });
        },
        handleReset(name) {
            this.$refs[name].resetFields();
            this.formData.desc = '';
        },
        handleUpload(file) {
            let _this = this;
            let nameArr = file.name.split('.');
            let fileType = nameArr[nameArr.length - 1];
            if (fileType !== 'json' && fileType !== 'JSON') {
                _this.$Message.error({
                    content: '请选择json文件',
                    duration: 5
                });
                return false;
            }
            this.formData.file = file;
            this.$refs.form.validateField('file');
            const reader = new FileReader();
            reader.readAsText(this.formData.file, 'UTF-8');
            reader.onload = function(evt) {
                let newjson = evt.target.result;
                _this.formData.detail = newjson;
                // this.result为读取到的json字符串，需转成json对象
                // 检测是否导入成功
            };
            let name = file.name;
            let fileName = name.substring(name.lastIndexOf('.') + 1).toLowerCase();
            if (
                fileName !== 'json' &&
                fileName !== 'JSON' &&
                fileName !== 'xml' &&
                fileName !== 'ymal' &&
                fileName !== 'sql'
            ) {
                this.formData.file = null;
                this.$Notice.warning({
                    title: '文件格式不正确',
                    desc: '文件格式' + file.name + '不正确，请导入.json/.xml/.ymal/.sql文件。'
                });
            }
            return false;
        }
    },
    mounted() {},
    created() {}
};
</script>
<style scoped>
.add-template-wrapper {
  /* padding: 10px 6px; */
  /* background: var(--card-body-bgcolor); */
}
.warn-tip {
  color: #f90;
  word-break: break-all;
}
.error-tip {
  color: #ed4014;
}
/deep/.add-template-wrapper
  .ivu-form-item:not(.ivu-form-item-required)
  .ivu-form-item-label::before {
  display: none;
}
</style>
